﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace FrameWork.Config
{
    /**
     * 日期帮助类
     */
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        /**
         * 定义规则
         */
        private static readonly string[] DateFormat =
        {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd",
        };

        /**
         * 重写读取
         */
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var dateString = reader.GetString();
            foreach (var dateFormat in DateFormat)
            {
                if (DateTime.TryParseExact(dateString, dateFormat, null, DateTimeStyles.None, out var dateTime))
                {
                    return dateTime;
                }
            }
            throw new JsonException("日期格式有误");
        }

        /**
         * 重写编辑
         */
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(DateFormat[0]));
            //writer.WriteStringValue(value.ToUniversalTime().ToString(DateFormat[0]));
        }
    }
}
